
package net.swa.dewei.web.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import net.swa.dewei.beans.entity.District;
import net.swa.dewei.beans.entity.FuwuZhan;
import net.swa.dewei.beans.vo.ZTreeNode;
import net.swa.dewei.service.FuwuZhanService;
import net.swa.system.beans.entity.User;
import net.swa.system.service.ICommonService;
import net.swa.system.util.SysConst;
import net.swa.system.util.annotation.Log;
import net.swa.system.web.action.AbstractBaseAction;
import net.swa.util.HtmlUtil;
import net.swa.util.StringUtil;

/**门店信息表 Action**/
public class FuwuzhanAction extends AbstractBaseAction
{
    private static final long serialVersionUID = 1908627223355967719L;

    private static final Logger log = Logger.getLogger(FuwuzhanAction.class);

    private FuwuZhan model;

    //服务站用户
    private User user;

    //实体类id
    private Long id;

    private String password;

    //批量删除的id集合
    private Long[] ids;

    /**省列表**/
    private List<District> provinceList;

    /**市列表*/
    private List<District> cityList;

    /**县区列表*/
    private List<District> areaList;

    /**县区列表*/
    private String areas;

    /**县区编码列表*/
    private String codes;

    /** 公用方法接口 */
    private ICommonService commonService;

    private FuwuZhanService fuwuZhanService;

    private File file;

    private String fileFileName;

    @Required
    @Resource
    public void setCommonService(ICommonService commonService)
    {
        this.commonService = commonService;
    }

    public Long getId()
    {

        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public Long[] getIds()
    {
        return ids;
    }

    public void setIds(Long[] ids)
    {
        this.ids = ids;
    }

    /**检测登录名是否已经被使用**/
    public String checkUserId() throws Exception
    {
        User u = getCurrentUser();
        if (null != u)
        {
            String loginName = model.getLoginName();
            List<User> list = commonService.search("userid", loginName, User.class);
            outString((list.size() == 0) + "");
            return null;
        }
        else
        {
            return LOGIN;
        }
    }

    /**初始化页**/
    public String initPage()
    {
        User u = getCurrentUser();
        if (null != u)
        {
            if (SysConst.USER_TYPE_ADMIN == u.getUserType())
            {
                //管理员用户操作信息
                return "message";
            }
            else if (SysConst.USER_TYPE_FUWUZHAN == u.getUserType())
            {
                //如果是服务站，则查询服务站信息
                model = fuwuZhanService.process(u.getId(), u.getFuwuzhanId());
                u.setFuwuzhanId(model.getId());
                return "toEdit";
            }
        }
        return LOGIN;
    }

    /**初始化页**/
    public String listPage()
    {
        provinceList = commonService.search("pid", "0", District.class);
        return "listPage";
    }

    /**去新增或者修改页面**/
    public String toEdit() throws Exception
    {
        provinceList = commonService.search("pid", "0", District.class);
        if (null != id)
        {
            model = commonService.commonFind(FuwuZhan.class, id);
            cityList = commonService.search(District.class, new String[] { "pname", "level" }, new Object[] { model.getProvince(), 2 });
            areaList = commonService.search(District.class, new String[] { "pname", "level" }, new Object[] { model.getCity(), 3 });
            return "toEdit";
        }
        else
        {
            model = new FuwuZhan();
            return "toEdit";
        }
    }

    /**
     * 去修改密码的页面
     */
    public String toResetPwd()
    {
        return "toResetPwd";
    }

    public String doResetPwd() throws Exception
    {
        if (fuwuZhanService.batchUpdate(ids, password))
        {
            outSuccess();
        }
        else
        {
            outError("error");
        }
        return null;
    }

    /**新增或者修改**/
    public String saveFuwuzhan() throws Exception
    {
        if (null == model.getId())
        {
            if (fuwuZhanService.saveModelExt(model, areas, codes))
            {
                //TODO 发邮件
                try
                {
                    User u = getCurrentUser();
                    sendMail(model, u);
                }
                catch (Exception e)
                {
                    log.debug("发送邮件异常,但不影响其他");
                }
                outSuccess();
            }
            else
            {
                outError("error");
            }
        }
        else
        {
            //            commonService.commonUpdate(model);
            //            outSuccess();
            if (fuwuZhanService.updateModelExt(model, areas, codes))
            {
                outSuccess();
            }
            else
            {
                outError("error");
            }
        }
        return null;
    }

    /**
     * 发送email
     * @param model2 
     * @param user
     * @throws Exception 
     * @throws Exception
     */
    private void sendMail(FuwuZhan model , User u) throws Exception
    {
        Properties prop = new Properties();
        String path = HtmlUtil.class.getClassLoader().getResource("mail.properties").getFile();
        prop.load(new FileInputStream(path));
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(prop.getProperty("host"));
        mailSender.setUsername(prop.getProperty("fromEmail"));
        mailSender.setPassword(prop.getProperty("password"));
        Properties property = new Properties();
        property.setProperty("mail.smtp.auth", "true");
        mailSender.setJavaMailProperties(property);
        MimeMessage mine = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mine, true, "utf-8");
        helper.setFrom(prop.getProperty("fromEmail"));
        helper.setTo(prop.getProperty("toEmail"));
        String cc = prop.getProperty("ccEmail");
        if (!StringUtils.isBlank(cc))
        {
            helper.setCc(cc);
        }
        helper.setSubject("你好，尊敬的客户！");
        String html = HtmlUtil.parseHtmlFile("net/swa/util/newFwz.html", model);
        helper.setText(html, true);
        mailSender.send(mine);
    }

    /** * 删除方法**/

    public String delete() throws Exception
    {
        if (fuwuZhanService.delete(ids))
        {
            outSuccess();
        }
        else
        {
            outError("ERROR");
        }
        return null;
    }

    @Log(description = "根据服务站加载区域树")
    public String queryTreeNodesJson() throws Exception
    {
        List<ZTreeNode> list = fuwuZhanService.queryTreeNodesJson(id);
        if (list.size() > 0)
        {
            outJson(list);
        }
        else
        {
            outError("没有");
        }
        return null;
    }

    //?
    public String queryByAdmin() throws Exception
    {
        String mysql = getRequestParameter("mysql");
        if (!StringUtils.isBlank(mysql))
        {
            Map<?, ?> map = commonService.addByAdmin(mysql);
            outJson(map);
        }
        else
        {
            outError("error");
        }
        return null;
    }

    public String updateJiebang() throws Exception
    {
        if (fuwuZhanService.updateJiebang(ids))
        {
            outSuccess();
        }
        else
        {
            outError("ERROR");
        }
        return null;
    }

    public String exportExcel()
    {
        String province = getRequestParameter("province");
        String city = getRequestParameter("city");
        String town = getRequestParameter("town");
        String name = getRequestParameter("name");
        //根据多条件导出
        HSSFWorkbook workbook = fuwuZhanService.exportExcel(name, province, city, town);
        HttpServletResponse response = getResponse();
        BufferedOutputStream bos = null;
        try
        {
            response.setContentType("application/vnd.ms-excel");
            String filename = new String("filename".getBytes("gbk"), "iso-8859-1") + ".xls";
            response.setHeader("Content-disposition", "attachment;filename=" + filename);
            bos = new BufferedOutputStream(response.getOutputStream());
            workbook.write(bos);
            bos.flush();
            removeSessionAttribute("listSheet");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.debug("服务站导出出错：" + e);
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }

    public String exportTemplate()
    {
        String path = getSession().getServletContext().getRealPath("/templates/fuwuzhan.xls");
        BufferedOutputStream bos = null;
        try
        {
            HttpServletResponse response = getResponse();
            // path是指欲下载的文件的路径。 
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");

            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(buffer);
            bos.flush();
            bos.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }

    public String exportErrorFile()
    {
        String path = getSession().getServletContext().getRealPath("/templates/fuwuzhan.xls");
        if (!StringUtils.isBlank(fileFileName))
        {
            path = fileFileName;
        }
        BufferedOutputStream bos = null;
        try
        {
            HttpServletResponse response = getResponse();
            // path是指欲下载的文件的路径。 
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");

            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(buffer);
            bos.flush();
            bos.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }

    public String toImpFwzExcel()
    {
        return "import";
    }

    public String impFwzExcel() throws Exception
    {
        Map<String, Object> map = null;
        String errFilePath = ServletActionContext.getServletContext().getRealPath("/uploads/error/");
        if (null != file && (!file.toString().equals("")))
        {
            String path = uploadFile();
            if (!StringUtils.isBlank(path))
            {
                map = fuwuZhanService.addExcel(path, errFilePath);
            }
            else
            {
                map = new HashMap<String, Object>();
                map.put("success", false);
                map.put("message", "文件上传失败");
            }
        }
        else
        {
            map = new HashMap<String, Object>();
            map.put("success", false);
            map.put("message", "请选择按模板格式的文件上传");
        }
        outJson(map);
        return null;
    }

    /**
     * 上传文件
     * @return
     */
    private String uploadFile()
    {
        String code = StringUtil.getRandomString(5) + System.currentTimeMillis();
        String realpath = ServletActionContext.getServletContext().getRealPath("/uploads/");
        try
        {
            File saveFile = new File(new File(realpath), fileFileName.substring(0, fileFileName.length() - 4) + code + ".xls");
            if (saveFile.exists())
            {
                saveFile.delete();
            }
            file.renameTo(saveFile);
            return realpath + File.separator + fileFileName.substring(0, fileFileName.length() - 4) + code + ".xls";
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "false";
    }

    public FuwuZhan getModel()
    {
        return model;
    }

    public void setModel(FuwuZhan model)
    {
        this.model = model;
    }

    public FuwuZhanService getFuwuZhanService()
    {
        return fuwuZhanService;
    }

    @Required
    @Resource
    public void setFuwuZhanService(FuwuZhanService fuwuZhanService)
    {
        this.fuwuZhanService = fuwuZhanService;
    }

    public ICommonService getCommonService()
    {
        return commonService;
    }

    public User getUser()
    {
        return user;
    }

    public void setUser(User user)
    {
        this.user = user;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public List<District> getProvinceList()
    {
        return provinceList;
    }

    public void setProvinceList(List<District> provinceList)
    {
        this.provinceList = provinceList;
    }

    public List<District> getCityList()
    {
        return cityList;
    }

    public void setCityList(List<District> cityList)
    {
        this.cityList = cityList;
    }

    public List<District> getAreaList()
    {
        return areaList;
    }

    public void setAreaList(List<District> areaList)
    {
        this.areaList = areaList;
    }

    public String getAreas()
    {
        return areas;
    }

    public void setAreas(String areas)
    {
        this.areas = areas;
    }

    public String getCodes()
    {
        return codes;
    }

    public void setCodes(String codes)
    {
        this.codes = codes;
    }

    public File getFile()
    {
        return file;
    }

    public void setFile(File file)
    {
        this.file = file;
    }

    public String getFileFileName()
    {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName)
    {
        this.fileFileName = fileFileName;
    }

}
